'''
https://leetcode.cn/problems/count-complete-tree-nodes/?envType=study-plan-v2&envId=top-interview-150
'''

# Definition for a binary tree node.
class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right
class Solution:
    # 最差情况：就是最后一层只有一个小根
    #           每次都必定砍掉一半，只会走一侧
    def countNodes(self, root: TreeNode) -> int:
        if not root: return 0
        lh = rh = 0
        cur = root
        while cur:
            lh += 1
            cur = cur.left
        cur = root
        while cur:
            rh += 1
            cur = cur.right
        if lh == rh:    # 满二叉树，往左往右来到这里，必定至少有一方会命中这里
            return 2 ** lh - 1
        return 1 + self.countNodes(root.left) + self.countNodes(root.right)

    def countNodes2(self, root: TreeNode) -> int:
        def f(root):
            if not root: return 0
            return 1 + f(root.left) + f(root.right)
        return f(root)


